package com.daoshu.system.utils;

import com.alibaba.fastjson.JSON;
import com.daoshu.component.exception.BusinessException;
import com.daoshu.component.jwt.JwtTokenFactory;
import com.daoshu.system.bo.AccountBo;
import com.daoshu.system.constants.ClientType;
import eu.bitwalker.useragentutils.DeviceType;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Component
@Slf4j
public class RequestUtils {

	@Autowired 
	private StringRedisTemplate redisTemplate;
	
	/**
	 * 用户登录后从redis获取用户信息
	 * @return
	 */
	public AccountBo getCurrentUser(){
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes sra = (ServletRequestAttributes) ra;
	    HttpServletRequest request = sra.getRequest();
		String token = request.getHeader(JwtTokenFactory.HEADER_STRING);
		if(StringUtils.isEmpty(token)) {
			log.error("token is empty");
			throw new BusinessException(HttpStatus.SC_UNAUTHORIZED, "不合法的请求，请验证是否登陆");
		}
		Set<String> keys = redisTemplate.keys( "*" + token);
		AccountBo account = null;
		if (keys.size() < 1) {
			log.error("get token from redis failed");
			throw new BusinessException(HttpStatus.SC_UNAUTHORIZED, "不合法的请求，请验证是否登陆");
		}
		for(String str : keys) {
			account = JSON.parseObject((String)redisTemplate.opsForValue().get(str), AccountBo.class ) ;
		}
		if (null == account) {
			log.error("用户未登录或者已经过期");
			throw new BusinessException(HttpStatus.SC_UNAUTHORIZED, "用户未登录或者已经过期");
		}
		return account;
	}
	
	
	/**
	 * 用户登录后从redis获取用户信息
	 * @return
	 */
	public AccountBo getCurrentUser(HttpServletRequest request){
		String token = request.getHeader(JwtTokenFactory.HEADER_STRING);
		System.out.println(request.getParameter("token"));
		if(StringUtils.isEmpty(token))
			return null;
		AccountBo account = JSON.parseObject((String)redisTemplate.opsForValue().get(token), AccountBo.class ) ;
		if (null == account) {
			throw new BusinessException(HttpStatus.SC_UNAUTHORIZED, "用户未登录或者已经过期");
		}
		return account;
	}
	/**
	 * 根据用户名获取 
	 * @param request
	 * @return
	 */
	public AccountBo getUser(String loginName){
		if(StringUtils.isEmpty(loginName))
			return null;
		String json = Optional.ofNullable(redisTemplate.opsForHash().get("LOGIN_NAME_BO", loginName)).orElse("").toString();
		AccountBo account = JSON.parseObject(json, AccountBo.class ) ;
		if (null == account) {
			log.error("缓存中没有获取到用户信息");
		}
		return account;
	}
	/**
	 * 获取IP
	 * @return
	 */
	public  String getCurrentIp(){
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes sra = (ServletRequestAttributes) ra;
	    HttpServletRequest request = sra.getRequest();
	    String ip = request.getHeader("X-Forwarded-For");  
	    Enumeration<String> headers = request.getHeaderNames();
	    String h = "";
	    while(headers.hasMoreElements()) {
	    	h = headers.nextElement();
	    	Enumeration<String> result = request.getHeaders(h);
	    	System.out.println(h+" :"+ request.getHeaders(h));
	    	while(result.hasMoreElements()) {
	    		System.out.println(result.nextElement());
	    	}
	    }
	    		
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_CLIENT_IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getRemoteAddr();  
        }
        return ip;   
	}
	
	
	/**
	 * 获取访问url
	 * @return
	 */
	public  String getRequestURI(){
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes sra = (ServletRequestAttributes) ra;
	    HttpServletRequest request = sra.getRequest();
	    return request.getRequestURI();
	 
	}
	
	/**
	 * 获取设备类型
	 * @return
	 */
	public ClientType geClientType() {
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes sra = (ServletRequestAttributes) ra;
		HttpServletRequest request = sra.getRequest();
		UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
		DeviceType type = userAgent.getOperatingSystem().getDeviceType();
		if(DeviceType.MOBILE.equals(type)) { // 移动端
			return ClientType.PHONE_CLIENT;
		}else if(DeviceType.COMPUTER.equals(type)) {
			return ClientType.AGENT_CLIENT;
		}else {
			return ClientType.UNKNOW_CLIENT;
		}
		/*String agent = Optional.ofNullable(request.getHeader("User-Agent")).orElseThrow(()->{
			return new BusinessException(500, "未知客户端类型");
		});  
		if (agent.toLowerCase().indexOf("androidlinuxiphoneipad")>0) {
			return ClientType.PHONE_CLIENT;
		}else if (agent.toLowerCase().indexOf("windows")>0) {
			return ClientType.AGENT_CLIENT;
		}else {
			return ClientType.UNKNOW_CLIENT;
		}*/
	}
}
